package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LiuWeiApplicationContext {

    private Class configClass;

    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList=new ArrayList<>();

    public LiuWeiApplicationContext(Class configClass) {
        this.configClass = configClass;

        //解析配置类
        //ComponentScan注解--->扫描路径--->扫描--->beanDefinition --->beanDefinitionMap
        scan(configClass);

        for(Map.Entry<String,BeanDefinition> entry:beanDefinitionMap.entrySet()){
            String beanName=entry.getKey();
            BeanDefinition beanDefinition=entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                Object bean= createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }

    private Object createBean(String beanName,BeanDefinition beanDefinition){
        Class clazz=beanDefinition.getClazz();
        try{
            Object instance=clazz.getDeclaredConstructor().newInstance();

            //依赖注入
            for(Field declaredField:clazz.getDeclaredFields()){
                if(declaredField.isAnnotationPresent(Autowired.class)){
                    Object bean=getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);
                }
            }

            //aware回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            //初始化前
            for(BeanPostProcessor beanPostProcessor:beanPostProcessorList){
                instance=beanPostProcessor.postProcessBforeInitialization(instance,beanName);
            }

            //初始化
            if(instance instanceof  InitializingBean){
                try{
                    ((InitializingBean)instance).afterPropertiesSet();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            //初始化后
            for(BeanPostProcessor beanPostProcessor:beanPostProcessorList){
                instance=beanPostProcessor.postProcessAfterInitialization(instance,beanName);
            }
            return instance;
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    private void scan(Class configClass) {
        ComponentScan componentScan = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path = componentScan.value();
        path = path.replace(".", "/");
        //类加载器
        ClassLoader classLoader = LiuWeiApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(path);
        //转化为文件
        File file = new File(resource.getFile());
        if (file.isDirectory()) {
            //将包下面的每一个类作为文件
            File[] files = file.listFiles();
            for (File f : files) {
                String fileName = f.getAbsolutePath();
                if (fileName.endsWith(".class")) {
                    //调整路径格式
                    String className = fileName.substring(fileName.indexOf("com"), fileName.indexOf(".class"));
                    className = className.replace("\\", ".");
                    //System.out.println(className);

                    try{
                        Class<?> clazz=classLoader.loadClass(className);
                        //System.out.println(clazz);
                        if(clazz.isAnnotationPresent(Component.class)){
                            //表示当前类是一个Bean
                            //判断这个类是不是单例类

                            if(BeanPostProcessor.class.isAssignableFrom(clazz)){
                                BeanPostProcessor instance=(BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorList.add(instance);
                            }
                            Component componentAnnotation=clazz.getDeclaredAnnotation(Component.class);
                            String beanName=componentAnnotation.value();

                            BeanDefinition beanDefinition=new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            if(clazz.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation=clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            }else{
                                //默认为单例
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    }catch (ClassNotFoundException e){
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public Object getBean(String beanName) {
        if(beanDefinitionMap.containsKey(beanName)){
            BeanDefinition beanDefinition=beanDefinitionMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){
                Object o=singletonObjects.get(beanName);
                return o;
            }else{
                Object bean=createBean(beanName,beanDefinition);
                return bean;
            }
        }else{
            //不存在对应bean
            throw new NullPointerException();
        }
    }
}

